import { format } from 'date-fns'

/**
 * 解析工时数据
 * @param {Array} rawData - 原始Excel数据
 * @returns {Array} 解析后的工时数据
 */
export const parseWorkTimeData = (rawData) => {
  if (!rawData || !Array.isArray(rawData)) {
    throw new Error('数据格式错误')
  }

  return rawData
    .map((row, index) => {
      // 处理可能的不同数据格式
      let id,
        date,
        content,
        hours,
        remaining,
        object,
        product,
        executor,
        project

      if (Array.isArray(row)) {
        // 数组格式数据
        [
          id,
          date,
          content,
          hours,
          remaining,
          object,
          product,
          executor,
          project,
        ] = row
      } else if (typeof row === 'object') {
        // 对象格式数据
        id = row.编号 || row.id || row.ID || index + 1
        date = row.日期 || row.date || row.Date
        content = row.工作内容 || row.content || row.Content || ''
        hours = row.耗时 || row.hours || row.Hours || 0
        remaining = row.剩余 || row.remaining || row.Remaining || 0
        object = row.对象 || row.object || row.Object || ''
        product = row.产品 || row.product || row.Product || ''
        executor = row.执行 || row.executor || row.Executor || ''
        project = row.项目 || row.project || row.Project || ''
      } else {
        throw new Error(`第${index + 1}行数据格式错误`)
      }

      // 数据验证和格式化
      const parsedData = {
        id: String(id || index + 1),
        date: formatDate(date),
        content: String(content || ''),
        hours: parseFloat(hours) || 0,
        remaining: parseFloat(remaining) || 0,
        object: String(object || ''),
        product: String(product || ''),
        executor: String(executor || ''),
        project: String(project || ''),
        // 添加一些计算字段
        weekDay: getWeekDay(date),
        month: getMonth(date),
        year: getYear(date),
      }

      return parsedData
    })
    .filter((item) => item.date) // 过滤无效数据
}

/**
 * 格式化日期
 * @param {string|Date} date - 日期
 * @returns {string} 格式化后的日期字符串
 */
export const formatDate = (date) => {
  if (!date) return ''

  try {
    let dateObj

    if (typeof date === 'string') {
      // 处理各种日期格式
      if (date.includes('/')) {
        dateObj = new Date(date)
      } else if (date.includes('-')) {
        dateObj = new Date(date)
      } else if (date.length === 8) {
        // YYYYMMDD格式
        const year = date.substring(0, 4)
        const month = date.substring(4, 6)
        const day = date.substring(6, 8)
        dateObj = new Date(`${year}-${month}-${day}`)
      } else {
        dateObj = new Date(date)
      }
    } else if (date instanceof Date) {
      dateObj = date
    } else if (typeof date === 'number') {
      // Excel序列号转日期
      dateObj = new Date((date - 25569) * 86400 * 1000)
    } else {
      dateObj = new Date(date)
    }

    if (isNaN(dateObj.getTime())) {
      throw new Error('无效日期')
    }

    return format(dateObj, 'yyyy-MM-dd')
  } catch (error) {
    console.error('日期格式化错误:', error, date)
    return ''
  }
}

/**
 * 获取星期几
 * @param {string|Date} date - 日期
 * @returns {string} 星期几
 */
export const getWeekDay = (date) => {
  try {
    const dateObj = new Date(date)
    const weekDays = [
      '星期日',
      '星期一',
      '星期二',
      '星期三',
      '星期四',
      '星期五',
      '星期六',
    ]
    return weekDays[dateObj.getDay()]
  } catch (error) {
    return ''
  }
}

/**
 * 获取月份
 * @param {string|Date} date - 日期
 * @returns {string} 月份
 */
export const getMonth = (date) => {
  try {
    const dateObj = new Date(date)
    return format(dateObj, 'yyyy-MM')
  } catch (error) {
    return ''
  }
}

/**
 * 获取年份
 * @param {string|Date} date - 日期
 * @returns {string} 年份
 */
export const getYear = (date) => {
  try {
    const dateObj = new Date(date)
    return format(dateObj, 'yyyy')
  } catch (error) {
    return ''
  }
}

/**
 * 生成唯一ID
 * @returns {string} 唯一ID
 */
export const generateUniqueId = () => {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}

/**
 * 验证工时数据
 * @param {Object} data - 工时数据
 * @returns {boolean} 是否有效
 */
export const validateWorkTimeData = (data) => {
  if (!data || typeof data !== 'object') {
    return false
  }

  // 必填字段验证
  if (!data.date || !data.content) {
    return false
  }

  // 日期格式验证
  if (isNaN(new Date(data.date).getTime())) {
    return false
  }

  // 工时数值验证
  if (data.hours !== undefined && (isNaN(data.hours) || data.hours < 0)) {
    return false
  }

  return true
}

/**
 * 创建默认工时记录
 * @param {Object} overrides - 覆盖的字段
 * @returns {Object} 工时记录
 */
export const createDefaultWorkTimeRecord = (overrides = {}) => {
  return {
    id: generateUniqueId(),
    date: format(new Date(), 'yyyy-MM-dd'),
    content: '',
    hours: 0,
    remaining: 0,
    object: '',
    product: '',
    executor: '',
    project: '',
    weekDay: getWeekDay(new Date()),
    month: getMonth(new Date()),
    year: getYear(new Date()),
    ...overrides,
  }
}
